package cn.iocoder.yudao.module.system.service.appupgradeinfo;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.appupgradeinfo.vo.AppUpgradeInfoPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.appupgradeinfo.vo.AppUpgradeInfoSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.appupgradeinfo.AppUpgradeInfoDO;
import cn.iocoder.yudao.module.system.dal.mysql.appupgradeinfo.AppUpgradeInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.APP_UPGRADE_INFO_NOT_EXISTS;

/**
 * app升级信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class AppUpgradeInfoServiceImpl implements AppUpgradeInfoService {

    @Resource
    private AppUpgradeInfoMapper appUpgradeInfoMapper;

    @Override
    public Long createAppUpgradeInfo(AppUpgradeInfoSaveReqVO createReqVO) {
        // 插入
        AppUpgradeInfoDO appUpgradeInfo = BeanUtils.toBean(createReqVO, AppUpgradeInfoDO.class);
        appUpgradeInfoMapper.insert(appUpgradeInfo);
        // 返回
        return appUpgradeInfo.getId();
    }

    @Override
    public void updateAppUpgradeInfo(AppUpgradeInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateAppUpgradeInfoExists(updateReqVO.getId());
        // 更新
        AppUpgradeInfoDO updateObj = BeanUtils.toBean(updateReqVO, AppUpgradeInfoDO.class);
        appUpgradeInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteAppUpgradeInfo(Long id) {
        // 校验存在
        validateAppUpgradeInfoExists(id);
        // 删除
        appUpgradeInfoMapper.deleteById(id);
    }

    private void validateAppUpgradeInfoExists(Long id) {
        if (appUpgradeInfoMapper.selectById(id) == null) {
            throw exception(APP_UPGRADE_INFO_NOT_EXISTS);
        }
    }

    @Override
    public AppUpgradeInfoDO getAppUpgradeInfo(Long id) {
        return appUpgradeInfoMapper.selectById(id);
    }

    @Override
    public PageResult<AppUpgradeInfoDO> getAppUpgradeInfoPage(AppUpgradeInfoPageReqVO pageReqVO) {
        return appUpgradeInfoMapper.selectPage(pageReqVO);
    }

    @Override
    public AppUpgradeInfoDO getAppUpgradeInfo() {
        List<AppUpgradeInfoDO> appUpgradeInfoDOS = appUpgradeInfoMapper.selectList();
        if (CollUtil.isNotEmpty(appUpgradeInfoDOS)) {
            return appUpgradeInfoDOS.get(0);
        }
        return null;
    }
}